import { Product, GetProductsParams, ProductStats } from '../types/product';
import { productData as mockProductData, getProductStats } from '../data/productData';

// API基础路径
const API_BASE = '/api/products';

// API响应接口
interface ApiResponse<T> {
  data: T;
  total: number;
  page: number;
  pageSize: number;
}

// 模拟产品API
const mockProductApi = {
  // 获取产品列表
  getProducts: async (params: GetProductsParams = {}): Promise<ApiResponse<Product[]>> => {
    const { page = 1, pageSize = 10, search, category, status } = params;
    
    // 过滤数据
    let filteredData = mockProductData;
    
    if (search) {
      filteredData = filteredData.filter(product => 
        product.name.includes(search) || 
        product.code.includes(search) ||
        product.description?.includes(search)
      );
    }
    
    if (category) {
      filteredData = filteredData.filter(product => product.category === category);
    }
    
    if (status) {
      filteredData = filteredData.filter(product => product.status === status);
    }
    
    // 分页
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedData = filteredData.slice(startIndex, endIndex);
    
    // 模拟延迟
    await new Promise(resolve => setTimeout(resolve, 300));
    
    return {
      data: paginatedData,
      total: filteredData.length,
      page,
      pageSize
    };
  },

  // 获取产品详情
  getProduct: async (id: number): Promise<Product> => {
    const product = mockProductData.find(p => p.id === id);
    if (!product) {
      throw new Error('产品不存在');
    }
    
    await new Promise(resolve => setTimeout(resolve, 200));
    return product;
  },

  // 创建产品
  createProduct: async (product: Omit<Product, 'id' | 'createdAt'>): Promise<Product> => {
    const newProduct: Product = {
      ...product,
      id: Math.max(...mockProductData.map(p => p.id)) + 1,
      createdAt: new Date().toISOString().split('T')[0]
    };
    
    mockProductData.push(newProduct);
    await new Promise(resolve => setTimeout(resolve, 500));
    
    return newProduct;
  },

  // 更新产品
  updateProduct: async (id: number, updates: Partial<Product>): Promise<Product> => {
    const index = mockProductData.findIndex(p => p.id === id);
    if (index === -1) {
      throw new Error('产品不存在');
    }
    
    const updatedProduct = {
      ...mockProductData[index],
      ...updates,
      updatedAt: new Date().toISOString().split('T')[0]
    };
    
    mockProductData[index] = updatedProduct;
    await new Promise(resolve => setTimeout(resolve, 300));
    
    return updatedProduct;
  },

  // 删除产品
  deleteProduct: async (id: number): Promise<void> => {
    const index = mockProductData.findIndex(p => p.id === id);
    if (index === -1) {
      throw new Error('产品不存在');
    }
    
    mockProductData.splice(index, 1);
    await new Promise(resolve => setTimeout(resolve, 200));
  },

  // 获取产品统计
  getProductStats: async (): Promise<ProductStats> => {
    await new Promise(resolve => setTimeout(resolve, 200));
    return getProductStats();
  }
};

// 真实产品API（根据配置决定使用模拟还是真实API）
const productApi = {
  getProducts: async (params: GetProductsParams = {}): Promise<ApiResponse<Product[]>> => {
    // 根据环境配置决定使用模拟API还是真实API
    const useMock = process.env.NODE_ENV === 'development' || !process.env.REACT_APP_API_BASE_URL;
    
    if (useMock) {
      return mockProductApi.getProducts(params);
    }
    
    // 真实API调用
    const queryParams = new URLSearchParams();
    if (params.page) queryParams.append('page', params.page.toString());
    if (params.pageSize) queryParams.append('pageSize', params.pageSize.toString());
    if (params.search) queryParams.append('search', params.search);
    if (params.category) queryParams.append('category', params.category);
    if (params.status) queryParams.append('status', params.status);
    
    const response = await fetch(`${API_BASE}?${queryParams}`);
    if (!response.ok) {
      throw new Error('获取产品列表失败');
    }
    
    return response.json();
  },

  getProduct: async (id: number): Promise<Product> => {
    const useMock = process.env.NODE_ENV === 'development' || !process.env.REACT_APP_API_BASE_URL;
    
    if (useMock) {
      return mockProductApi.getProduct(id);
    }
    
    const response = await fetch(`${API_BASE}/${id}`);
    if (!response.ok) {
      throw new Error('获取产品详情失败');
    }
    
    return response.json();
  },

  createProduct: async (product: Omit<Product, 'id' | 'createdAt'>): Promise<Product> => {
    const useMock = process.env.NODE_ENV === 'development' || !process.env.REACT_APP_API_BASE_URL;
    
    if (useMock) {
      return mockProductApi.createProduct(product);
    }
    
    const response = await fetch(API_BASE, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(product)
    });
    
    if (!response.ok) {
      throw new Error('创建产品失败');
    }
    
    return response.json();
  },

  updateProduct: async (id: number, updates: Partial<Product>): Promise<Product> => {
    const useMock = process.env.NODE_ENV === 'development' || !process.env.REACT_APP_API_BASE_URL;
    
    if (useMock) {
      return mockProductApi.updateProduct(id, updates);
    }
    
    const response = await fetch(`${API_BASE}/${id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(updates)
    });
    
    if (!response.ok) {
      throw new Error('更新产品失败');
    }
    
    return response.json();
  },

  deleteProduct: async (id: number): Promise<void> => {
    const useMock = process.env.NODE_ENV === 'development' || !process.env.REACT_APP_API_BASE_URL;
    
    if (useMock) {
      return mockProductApi.deleteProduct(id);
    }
    
    const response = await fetch(`${API_BASE}/${id}`, {
      method: 'DELETE'
    });
    
    if (!response.ok) {
      throw new Error('删除产品失败');
    }
  },

  getProductStats: async (): Promise<ProductStats> => {
    const useMock = process.env.NODE_ENV === 'development' || !process.env.REACT_APP_API_BASE_URL;
    
    if (useMock) {
      return mockProductApi.getProductStats();
    }
    
    const response = await fetch(`${API_BASE}/stats`);
    if (!response.ok) {
      throw new Error('获取产品统计失败');
    }
    
    return response.json();
  }
};

export { productApi };
export default productApi;